package com.zhangye.test.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhangye.test.mapper.AccountMapper;
import com.zhangye.test.mapper.AccountPayMapper;
import com.zhangye.test.mapper.AlipayOrderInfoMapper;
import com.zhangye.test.model.AccountPay;
import com.zhangye.test.model.AlipayOrderInfo;
import com.zhangye.test.model.Business;
import com.zhangye.test.util.RSA;
import com.zhangye.test.util.StringUtils;


@Service
public class AliPayVerifyServices {
	
	Logger logger = LoggerFactory.getLogger(AliPayVerifyServices.class);

	@Autowired
	private AlipayOrderInfoMapper aliPayOrderInfoMapper;

	@Autowired
	private AccountPayMapper accountPayMapper;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private PayListService payListService;

	@Autowired
	private BusinessService businessService;

	
	/**
	 * 修改支付成功后操作
	 * 作者： 张叶
	 * 创建时间：2018年6月4日  下午5:53:04
	 */
	@Transactional
	public Map<String, String> verifyNew(Map<String, Object> param) throws ParseException{

		AlipayOrderInfo ap;
		AccountPay acp;
		Map<String,Object>  response = new HashMap<String,Object>();
		Map<String,Object>  alipay = new HashMap<String,Object>();
		Map<String,String>  result = new HashMap<String,String>();
		result.put("resultCode", "1");
		
		response = JSONObject.fromObject(param.get("result"));
		alipay = (Map<String, Object>) response.get("alipay_trade_app_pay_response");//签名原始字符串
		String sign = (String) response.get("sign");
		String resultStatus = (String) param.get("resultStatus");//结果码
		double total_amount = Double.parseDouble((String) alipay.get("total_amount"));
		String order = "";
		if (param.get("order") != null && !"".equals(param.get("order"))) {
			order = (String) param.get("order");
		}
		String res = "";
		
		//验证签名是否合法
		if (RSA.verify(alipay.toString(), sign)) {
			String where = " and outTradeNo = '" + alipay.get("out_trade_no") + "'";
			where += " and totalAmount = " + total_amount;
			List<AlipayOrderInfo> list = aliPayOrderInfoMapper.selectByWhere(where);
			if (list.size() == 1) {
				String subject = list.get(0).getSubject();
				result.put("outTradeNo", alipay.get("out_trade_no").toString());
				if (alipay.get("seller_id").equals("2088421943565793")) {
					if (alipay.get("app_id").equals("2018060560269652")) {
						//判断订单是否处理过
						String where3 = " and outTradeNo = '" + alipay.get("out_trade_no") + "'";
							where3 += " and deleteLogo = '0'";
						List<AccountPay> accountp = accountPayMapper.selectByWhere(where3);
						if (accountp.size() > 0) {
							result.put("resultCode", "0");
							logger.info("重复订单，订单号：" + alipay.get("out_trade_no"));
						} else {
							if (resultStatus.equals("9000")) {
								acp = new AccountPay();
								acp.setUserid(list.get(0).getUserid());
								acp.setInserttime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
								acp.setTotalamount(Double.valueOf(total_amount));
								acp.setBalance(Double.valueOf(total_amount));
								acp.setVariation("+"+total_amount);
								acp.setPayway("支付宝支付");
								acp.setOuttradeno(alipay.get("out_trade_no").toString());
								acp.setPhporder(order);
								acp.setPhpresult(res);
								acp.setDeletelogo(0);
								if (accountPayMapper.insert(acp) > 0) {
									//支付成功更新业务表
									int b = 0;
									Long mId = (long)list.get(0).getUserid();
									Business bus = businessService.selectBymId(mId);
									if (bus == null || bus.equals("")) {
										if (subject.equals("挂机短信")) {
											bus.setMarketingStarttime(new Date());
											bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.getCurrentDateTime(), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
											bus.setWebsiteStarttime(new Date());
											bus.setWebsiteEndtime(new Date());
											bus.setCardStarttime(new Date());
											bus.setCardEndtime(new Date());
										} else {
											bus.setMarketingStarttime(new Date());
											bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.getCurrentDateTime(), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
											bus.setWebsiteStarttime(new Date());
											bus.setWebsiteEndtime(new Date());
											bus.setCardStarttime(new Date());
											bus.setCardEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.getCurrentDateTime(), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
										}
										bus.setDeletelogo(0);
										b = businessService.insert(bus);
									} else {
										Date now = new Date();
										if (subject.equals("挂机短信")) {
											Date marketingEndtime = bus.getMarketingEndtime();
											if(marketingEndtime.before(now)){
												bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
											}else{
												bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.formatDate(marketingEndtime, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
											}
										} else {
											Date cardEndTime = bus.getCardEndtime();
											if(cardEndTime.before(now)){
												bus.setCardEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
											}else{
												bus.setCardEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.formatDate(cardEndTime, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
											}
											Date marketingEndtime = bus.getMarketingEndtime();
											if(marketingEndtime.before(now)){
												bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
											}else{
												bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(list.get(0).getMonthcount(), StringUtils.formatDate(marketingEndtime, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
											}
										}
										b = businessService.update(bus);
									}
									if (b == 1) {
										result.put("resultCode", "0");
									} else {
										logger.info("交易成功，更新业务表business失败，订单号：" + alipay.get("out_trade_no"));
									}
								} else {
									logger.info("交易成功，插入account_pay表失败，订单号：" + alipay.get("out_trade_no"));
								}
							}
						}
					}
				}
			}
			//更新aliPay_orderInfo表
			ap = new AlipayOrderInfo();
			ap.setResultstatus(resultStatus);
			ap.setCode(alipay.get("code").toString());
			ap.setOuttradeno(alipay.get("out_trade_no").toString());
			ap.setUpdatetime(new Date());
			int i = aliPayOrderInfoMapper.updateByPrimaryKey(ap);
			if (i == 0) {
				logger.info("aliPay_orderInfo表更新失败，订单号：" + alipay.get("out_trade_no"));
			}
		} else {
			logger.info("签名验证失败，订单号：" + alipay.get("out_trade_no"));
		}
		return result;
	}
	
}
